package com.hlkj.pay.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hlkj.framework.common.pojo.CommonResult;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 微信OAuth2.0授权
 * 静默回去用户appid
 */
@Slf4j
public class WeChatOAuthUtils {

    public static String getAuthCode(String pubAppid, String redirectUrl) throws Exception {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("appid", pubAppid);
            params.put("redirect_uri", redirectUrl);
            params.put("response_type", "code");
            params.put("scope", "snsapi_base");
            params.put("state", "STATE#wechat_redirect");
            return "https://open.weixin.qq.com/connect/oauth2/authorize?" + mapToQuery(params);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    public static CommonResult<String> getOpenId(String pubAppid, String secretKey, String code) throws Exception {
        try {
            Map<String, String> accessMap = new HashMap<>();
            accessMap.put("appid", pubAppid);
            accessMap.put("secret", secretKey);
            accessMap.put("code", code);
            accessMap.put("grant_type", "authorization_code");
            String accessRes = requestGet("https://api.weixin.qq.com/sns/oauth2/access_token", accessMap);
            log.info("获取微信授权返回信息 ==>> " + accessRes);
            JSONObject accessObj = JSONUtil.parseObj(accessRes);
            if (accessObj.containsKey("errcode")) {
                return CommonResult.error(1, "获取授权失败错误码 " + accessObj.containsKey("errcode"));
            }
            return CommonResult.success(accessObj.getStr("openid"));
        } catch (Exception e) {
            return CommonResult.error(1, e.getMessage());
        }
    }

    private static String mapToQuery(Map<String, String> params) {
        StringBuilder queryString = new StringBuilder();
        Set<Map.Entry<String, String>> entrySet = params.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            String key = entry.getKey();
            String value = entry.getValue();
            // URL 编码
            String encodedKey = URLEncoder.encode(key);
            String encodedValue = URLEncoder.encode(value);
            if (queryString.length() > 0) {
                queryString.append("&");
            }
            queryString.append(encodedKey).append("=").append(encodedValue);
        }
        return queryString.toString();
    }

    private static String requestGet(String urlPath, Map<String, String> params) throws Exception {
        HttpURLConnection connection = null;
        try {

            // 创建URL对象，传入你想请求的URL
            URL url = new URL(urlPath + "?" + mapToQuery(params));

            log.info("获取微信授权请求链接 ==>> " + url);
            // 打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置请求方式为GET
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            // 设置请求超时
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 获取响应码
            int responseCode = connection.getResponseCode();
            // 如果响应码是200（成功），读取响应内容
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 创建BufferedReader来读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
                String inputLine;
                StringBuilder response = new StringBuilder();
                // 按行读取响应内容
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // 输出响应内容
                return response.toString();
            } else {
                throw new Exception("授权请求异常，" + responseCode);
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        } finally {
            if (connection != null) connection.disconnect();
        }
    }

    public static void main(String[] args) {

    }
}
